<template>
	<view>
		<template v-if="url">
			<web-view :src="url" @message="postMessage" id="myIframe"></web-view>
		</template>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				url:""
			}
		},
		onLoad() {
			this.getConfig();
		},
		methods: {
			getConfig(){
				this.$_request(
					"GET","/api/fresns/v1/global/configs",
					{
						"keys":"account_login_service"
					},
					(res) => {
						let webViewUrl = res.data.data.account_login_service;
						const regex = /^(https?:\/\/[^/]+)(\/.*)$/i;
						webViewUrl = webViewUrl.replace(regex, (_, domainPart, pathPart) => `${this.$_url()}${pathPart}`);
						webViewUrl = webViewUrl.replace('{accessToken}', this.$_extensionPluginAccessToken());
						webViewUrl = webViewUrl.replace('{postMessageKey}', 'youransns');
						webViewUrl = webViewUrl.replace('{redirectUrl}', '');
						this.url = webViewUrl;
						// #ifdef H5
						this.h5Login();
						// #endif
					}
				)
			},
			h5Login(){
				let url = this.$_url();
				let header = this.$_fresnsHeader();
				// 添加消息监听器
				window.addEventListener('message', receiveMessage, false);
				function receiveMessage(event) {
					if(JSON.parse(event.data).code === 0){
						uni.request({
							url:url + "/api/fresns/v1/account/auth-token",
							method:"POST",
							header:header,
							data:{
								"loginToken":JSON.parse(event.data).data.loginToken
							},
							success: (res) => {
								if(res.data.code === 0){
									const accountAuthToken = JSON.stringify(res.data.data.authToken);
									try {
										uni.setStorageSync('accountAuthToken', accountAuthToken);
										uni.switchTab({
											url:"/pages/my/my"
										})
									} catch (es) {
										uni.showToast({
											title: es,
											duration: 1500
										});
									}
								}else{
									uni.showToast({
										title: res.data.message,
										duration: 1500
									});
								}
							}
						})
					}else{
						uni.showToast({
							title: e,
							duration: 1500
						});
					}
				}
			},
			postMessage(e){
				if(JSON.parse(e.detail.data).code === 0){
					this.$_request(
						"POST","/api/fresns/v1/account/auth-token",
						{
							"loginToken":JSON.parse(e.detail.data).data.loginToken
						},
						(res) => {
							if(res.data.code === 0){
								const accountAuthToken = JSON.stringify(res.data.data.authToken);
								try {
									uni.setStorageSync('accountAuthToken', accountAuthToken);
									uni.switchTab({
										url:"/pages/my/my"
									})
								} catch (es) {
									uni.showToast({
										title: es,
										duration: 1500
									});
								}
							}else{
								uni.showToast({
									title: res.data.message,
									duration: 1500
								});
							}
						}
					)
				}else{
					uni.showToast({
						title: e,
						duration: 1500
					});
				}
			},
		}
	}
</script>

<style>

</style>
